<template>
    <div ref="chartRef" class="chart-container"></div>
</template>
  
<script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch, defineProps } from "vue";
import * as echarts from "echarts";
  
const props = defineProps<{
    options: echarts.EChartsOption;
}>()

const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

const initChart = () => {
    if (chartRef.value) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance.setOption(props.options);
        
        // 添加点击事件监听
        chartInstance.on('click', (params) => {
            const event = new CustomEvent('chartClick', {
                detail: {
                    dataIndex: params.dataIndex,
                    value: params.value,
                    seriesIndex: params.seriesIndex
                }
            });
            chartRef.value?.dispatchEvent(event);
        });
        chartInstance.resize(); // 强制刷新尺寸，解决移动端首次渲染不显示
    }
};

// 监听 options 变化
watch(() => props.options, (newOptions) => {
    if (chartRef.value && chartRef.value.offsetWidth === 0) {
        setTimeout(() => {
            if (chartRef.value && chartInstance) {
                chartInstance.resize();
                chartInstance.setOption(newOptions, true);
            }
        }, 300);
    } else {
        chartInstance?.setOption(newOptions, true);
        chartInstance?.resize();
    }
}, { deep: true });

onMounted(() => {
    initChart();
    window.addEventListener("resize", handleResize);
    setTimeout(() => {
        chartInstance?.resize();
    }, 300);
});
  
onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
    chartInstance?.dispose();
});

const handleResize = () => {
    chartInstance?.resize();
};
</script>
  
<style scoped>
.chart-container {
    width: 100%;
    height: 330px;
    padding-top: 20px;
    background-color: white;
}

.chart-container.home-chart {
    width: 560px;
}

.chart-container.trend-chart {
    width: 800px;
}

@media (max-width: 768px) {
    .chart-container,
    .chart-container.home-chart,
    .chart-container.trend-chart {
        width: 100% !important;
        min-width: 0 !important;
        height: 220px !important;
        padding-top: 8px !important;
        box-sizing: border-box;
    }
}
</style>
  